<?php

namespace backend\module\content\models;
use backend\module\content\models\ContentCategory;
use Yii;

/**
 * This is the model class for table "{{%article}}".
 *
 * @property int $id
 * @property string $title
 * @property int $catid
 * @property string $thumb
 * @property string $content
 * @property string $description
 * @property string $keywords
 * @property int $usreid
 * @property string $url
 */
class Article extends \yii\db\ActiveRecord
{   
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%article}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'catid', 'userid','region_id','map_lat','map_lng','shop_hours_start','shop_hours_end'], 'required'],
            [['catid', 'userid','sort'], 'integer'],
            [['content', 'description'], 'string'],
            [['title', 'thumb', 'keywords', 'url'], 'string', 'max' => 255],
            [['sort'],'default','value'=>100],
            [['created'],'default','value'=>function(){
                return time();
            }],
            ['catid','validatePermission'],
        ];
    }
    public function save($runValidation = true, $attributeNames = null){
        $this->created = $this->created?strtotime($this->created):null;
        return parent::save($runValidation,$attributeNames);
    }
    public function validatePermission($attribute, $params){
        if(!$this->hasErrors()){
            $category = ContentCategory::findOne($this->catid);
            if($category['userid'] != $this->userid){
                $this->addError($attribute, Yii::t('common', 'Error'));
            }
        }
        
        
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', 'ID'),
            'title' => Yii::t('common', 'Title'),
            'catid' => Yii::t('common', 'Category'),
            'thumb' => Yii::t('common', 'Thumb'),
            'content' => Yii::t('common', 'Content'),
            'description' => Yii::t('common', 'Description'),
            'keywords' => Yii::t('common', 'Keywords'),
            'userid' => Yii::t('common', 'Userid'),
            'url' => Yii::t('common', 'Url'),
            'sort' => Yii::t('common', 'Sort'),
            'created' => Yii::t('common', 'Create Time'),
            'date_range' => Yii::t('common', 'Data Range'),
            'region_id' => Yii::t('common', 'Region'),
            'map_lat' => Yii::t('common', 'Latitude'),
            'map_lng' => Yii::t('common', 'Longitude'),
            'shop_hours_start' => Yii::t('common', 'Shop Hours Start'),
            'shop_hours_end' => Yii::t('common', 'Shop Hours End'),
        ];
    }
}
